<template>
    <view>
        <!-- 凭据信息表单 -->
        <scroll-view class="list-scroll-content" scroll-y>
            <view class="cell-1">
                <!-- <button class="niceButton4" @click="selectGoodsShow=true">选择货物</button>-->
                <!-- <view class="info-item-content">
                <view class="product-selection">
                    <view v-for="(product, index) in productList" :key="index"
                        :class="['product-button', { active: selectedIds.includes(product.productId) }]"
                        @click="selectproduct(product, index)" v-show="isOpen || index<max">
                        {{ product.prodName }}
                    </view>
                    <view v-if="showMoreButton" @click="toggleView" class="more-button">
                        {{ isOpen ? '收起' : '更多' }}
                    </view>
                </view>
            </view> -->
                <view class="tit-1">
                    填写配送信息
                </view>
                <view class="content-1">
                    <view class="form-section">
                        <u-form :model="order" :rules="rules" ref="uForm">
                            <u-form-item label="配送货品" prop="prods">
                                <!-- <u-button @click="selectGoodsShow = true">点击选择/更改配送货物</u-button> -->
                                <!-- <view class="info-item-content">
                                    <view class="product-selection">
                                        <view v-for="(product, index) in selectedProds" :key="index"
                                            class="product-button">
                                            {{ product.prodName }}
                                        </view>
                                    </view>
                                </view> -->
                                <view class="selectGoods-info">
                                    <view class="info-item">
                                        <view class="info-item-content">
                                            <view class="product-selection">
                                                <view v-for="(product, index) in productList" :key="index"
                                                    :class="['product-button', { active: selectedIds.includes(product.prodId) }]"
                                                    @click="selectproduct(product, index)" v-show="isOpen || index<max">
                                                    {{ product.prodName }}
                                                </view>
                                                <view v-if="showMoreButton" @click="toggleView" class="more-button">
                                                    {{ isOpen ? '收起' : '更多' }}
                                                </view>
                                            </view>
                                        </view>
                                    </view>
                                </view>
                            </u-form-item>
                            <u-form-item label="档口号" prop="stallNum">
                                <u-picker :show="showStall" :columns="[stalls]" v-model="order.stallNum"
                                    @confirm="stallConfirm" @cancel='showStall = false'></u-picker>
                                <u-button @click="showStall = true"
                                    style=" font-size: 18px;">{{`${order.stallNum?order.stallNum: '00000'}`}}</u-button>
                            </u-form-item>
                            <u-form-item label="司机姓名" prop="senderName">
                                <u-input v-model="order.senderName" placeholder="输入司机姓名"></u-input>
                            </u-form-item>
                            <u-form-item label="司机电话" prop="senderPhone">
                                <u-input v-model="order.senderPhone" placeholder="输入司机电话" type="number"></u-input>
                            </u-form-item>
                            <u-form-item label="车牌号" prop="senderCar">
                                <!--                                <view class="plate-button plate-add-btn" :show="plateShow"
                                    @click="addPlateModel = true">
                                    {{`${order.senderCar?order.senderCar:'点击输入'}`}}
                                </view> -->
                                <u-input v-model="order.senderCar" placeholder="配送车牌号"
                                    @focus="addPlateModel = true"></u-input>

                            </u-form-item>
                            <u-form-item label="卸货时间">
                                <text class="date-time"
                                    @click="datetimePicker = true">{{`${order.unloadTime?order.unloadTime:'点击选择'}`}}</text>
                                <u-datetime-picker ref="datetimePicker" v-model="order.unloadTimeModel"
                                    :show="datetimePicker" mode="datetime" @cancel='datetimePicker = false'
                                    @confirm="datetimeConfirm" :formatter="datetimeFormatter" :show-seconds="false"
                                    :minuteInterval="10" :minDate='Number(new Date())'></u-datetime-picker>
                            </u-form-item>
                            <u-form-item label="订单备注">
                                <u-input v-model="order.note" placeholder="输入订单备注"></u-input>
                            </u-form-item>

                            <button class="u-reset-button" @click="submitOrder" type="default">提交</button>
                        </u-form>
                    </view>
                </view>

                <u-popup :show="selectGoodsShow" mode="bottom" @close="close" @open="open">
                    <view class="selectGoods-info">
                        <view class="info-item">
                            <view class="info-item-tip">
                                选择货品：
                            </view>
                            <view class="info-item-content">
                                <view class="product-selection">
                                    <view v-for="(product, index) in productList" :key="index"
                                        :class="['product-button', { active: selectedIds.includes(product.prodId) }]"
                                        @click="selectproduct(product, index)">
                                        {{ product.prodName }}
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <button class="u-reset-button" style="
				                                   width: 30%;
				                                   height: 37px;
				                                   line-height: 37px;
				                                   margin-bottom: 4vh;
				                                   transform: translateY(15px);
				" @click="submitSelect" type="default">确认</button>
                    <button class="u-reset-button" style="
				                                    width: 30%;
				                                    height: 37px;
				                                    line-height: 37px;
				                                    margin-bottom: 10vh;
				                                    transform: translateY(15px);
				" @click="close" type="default">关闭</button>
                </u-popup>
            </view>

            <TrailerKeyboard :show.sync="addPlateModel" :vehicleNo="newPlate" @confirm="addPlate" vehicleType="car">
            </TrailerKeyboard>
        </scroll-view>
        <tabBar></tabBar>

    </view>
</template>

<script>
    import TrailerKeyboard from "@/components/car-board/carBoard.vue";
    import {
        imageApi,
        orderApi,
        productApi,
        shopApi
    } from '@/api';
    export default {
        data() {
            return {
                max: 3, //默认显示几条数据
                isOpen: false, // 是否显示全部产品
                plateShow: true,
                showStall: false,
                datetimePicker: false,
                timePicker: false,
                save_timer: null,
                datetimesingle: '',
                selectGoodsShow: false,
                selectedIds: [],
                selectedStall: '',
                selectedProds: [],
                startTime: '',
                endTime: '',
                stalls: [],
                order: {
                    note: '',
                    prods: [],
                    senderCar: '',
                    senderName: '',
                    senderPhone: '',
                    shopId: 0,
                    stallNum: '',
                    unloadTime: '',
                    unloadTimeModel: null,
                    userId: '',
                    userName: '',

                },
                productList: [],
                selectedPlate: '', // 当前选择的车牌号
                rules: {
                    senderName: {
                        required: true,
                        message: '请填写司机姓名',
                        trigger: 'blur'
                    },
                    senderPhone: [{
                            required: true,
                            message: "手机号不能为空",
                            trigger: "blur"
                        },
                        {
                            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                            message: "请输入正确的手机号码",
                            trigger: "blur"
                        },
                    ],
                    stallNum: {
                        required: true,
                        message: '请选择档口号',
                        trigger: 'blur'
                    },
                    senderCar: {
                        required: true,
                        message: '请填写车牌号',
                        trigger: 'blur'
                    },
                    // prods: [
                    //     { required: true, message: '请至少选择一个配送货品', trigger: 'blur' }
                    // ],
                },
                addPlateModel: false,
                newPlate: '', // 新车牌输入框

            };
        },
        components: {
            TrailerKeyboard
        },
        methods: {
            onDateChange(event) {
                const chosenDate = event.detail.value; // 获取用户选择的时间
                this.selectedTime = chosenDate; // 更新显示的时间
            },
            setPickerRange() {
                const now = new Date();
                const currentDateTime = now.toISOString(); // 获取当前时间的 ISO 字符串

                // 计算十分钟后的时间
                const futureDateTime = new Date(now.getTime() + 10 * 60 * 1000).toISOString();

                this.startTime = currentDateTime;
                this.endTime = futureDateTime;
            },
            selectproduct(prod, index) {
                console.log(prod, index);
                const prodId = prod.prodId;
                const prodIndex = this.selectedProds.findIndex(p => p.prodId === prodId);
                if (prodIndex !== -1) {
                    this.selectedProds.splice(prodIndex, 1); //删除
                } else {
                    this.selectedProds.push(prod);
                }

                if (this.selectedIds.includes(prod.prodId)) {
                    this.selectedIds = this.selectedIds.filter(id => id !== prod.prodId);
                } else {
                    this.selectedIds.push(prod.prodId);
                }

                console.log('selectedProds', this.selectedProds);
            },
            submitSelect() {
                this.selectedProds = this.productList.filter(item => this.selectedIds.includes(item.prodId));
                console.log(this.selectedProds);
                this.selectGoodsShow = false;
            },
            async submitOrder() {
                this.order.userId = this.userInfo.userId;
                this.order.shopId = this.userInfo.shopId;
                this.order.prods = this.selectedProds;
                this.order.userName = this.userInfo.userName;
				console.log(this.order);
                console.log(this.selectedProds);
                uni.showLoading({
                    title: "请稍后"
                });
                try {
                    const {
                        code,
                        data,
                        message
                    } = await orderApi.createOrder({
                        ...this.order,
                        note: this.order.note || '无'
                    });
                    uni.hideLoading();
                    uni.setStorageSync('orderData', JSON.stringify(this.order));
                    if (code === 200) {
                        // 处理成功逻辑，例如跳转或提示
                        uni.showToast({
                            title: '订单创建成功',
                            icon: 'success'
                        });
                        this.order = {
                            ...this.order,
                            note: '',
                            senderCar: '',
                            senderName: '',
                            senderPhone: '',
                            unloadTime: '',
                            unloadTimeModel: null,
                        };
                        // this.order.unloadTimeModel = Number(new Date());
                        // this.$refs.datetimePicker.confirm();
                        uni.switchTab({
                            url: '/pages/merchant/order'
                        })
                    } else {
                        // 处理错误逻辑
                        uni.showToast({
                            title: message || '创建订单失败',
                            icon: 'none'
                        });
                    }
                } catch (error) {
                    uni.hideLoading();
                    console.log(error)
                    uni.showToast({
                        title: '请求失败',
                        icon: 'none'
                    });
                }
            },

            changeLog(e) {
                console.log("发生事件", e);
            },
            open() {
                // console.log('open');
            },
            close() {
                this.selectGoodsShow = false
                // console.log('close');
            },
            datetimeConfirm(e) {
                const timeFormat = uni.$u.timeFormat;
                const timeFormated = timeFormat(e.value, 'yyyy-mm-dd hh:MM:00');
                console.log(timeFormated);
                this.order.unloadTime = timeFormated;
                console.log(this.order.unloadTime)
                this.datetimePicker = false;
            },
            stallConfirm(e) {
                console.log(e.value)
                this.order.stallNum = e.value.join(',');
                this.showStall = false;
            },
            datetimeFormatter(type, value) {
                if (type === 'year') {
                    return `${value}年`
                }
                if (type === 'month') {
                    return `${value}月`
                }
                if (type === 'day') {
                    return `${value}日`
                }
                if (type === 'hour') {
                    return `${value}时`
                }
                if (type === 'minute') {
                    return `${value}分`
                }
                return value
            },
            formatDate(date) {
                // 格式化日期为 'yyyy-mm-dd hh:MM'
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');

                return `${year}-${month}-${day} ${hours}:${minutes}`;
            },
            parseDateTime(datetimeStr) {
                // 使用正则表达式解析日期和时间部分
                const [datePart, timePart] = datetimeStr.split(' ');
                const [year, month, day] = datePart.split('-').map(Number);
                const [hours, minutes] = timePart.split(':').map(Number);

                // 创建 Date 对象，月份需要减 1 因为 JavaScript 的月份是从 0 开始的
                const date = new Date(year, month - 1, day, hours, minutes);

                // 返回时间戳
                return date.getTime();
            },
            // selectproduct(prod, index) {
            //     if (this.selectedIds.includes(prod.prodId)) {
            //         this.selectedIds = this.selectedIds.filter(id => id !== prod.prodId);
            //     } else {
            //         this.selectedIds.push(prod.prodId);
            //     }
            // },
            selectGoods(selectItem) {
                this.currOrder = selectItem;
                console.log(`this.currOrder.orderId:${this.currOrder.orderId}`)
                this.allocationShow = true;

            },
            addPlate(plateInput) {
                if (plateInput) {
                    this.order.senderCar = plateInput;
                    this.$refs.uForm.validate().then(res => {
                        console.log('校验通过')
                    }).catch(errors => {
                        console.log('校验失败')
                    })
                    this.plateShow = false;
                }
            },
            async fetchProductList() {
                try {
                    uni.showLoading({
                        title: "请稍后"
                    })
                    const {
                        code,
                        data
                    } = await productApi.fetchProductList();

                    if (code == 200) {
                        data.map(item => ({
                            ...item,
                            // priceRules: this.parsePriceRules(item.priceRules, item.prodPrice),
                            // selectedRuleIndex: 0, //默认选择第一个规则
                            // prodCount: 1 //初始1个
                        }));
                        this.productList = data;
                        // console.log("data:"+this.productList[0].priceRules);
                        // console.log(JSON.stringify(this.productList[0].priceRules, null, 2))
                        // console.log(JSON.stringify(this.productList, null, 2));
                    }
                } finally {
                    uni.hideLoading();
                }

            },
            async fetchShopProductList(id) {
                console.log(id);
                try {
                    uni.showLoading({
                        title: "请稍后"
                    })
                    const {
                        code,
                        data
                    } = await productApi.fetchShopProductList(id);
                    if (code == 200) {
                        this.productList = data.map(item => ({
                            ...item,
                            priceRules: this.parsePriceRules(item.priceRules, item.prodPrice),
                            selectedRuleIndex: 0, //默认选择第一个规则
                            prodCount: 1 //初始1个
                        }));
                        // console.log("data:"+this.productList[0].priceRules);
                        // console.log(JSON.stringify(this.productList[0].priceRules, null, 2))
                        // console.log(JSON.stringify(this.productList, null, 2));
                    }
                } finally {
                    uni.hideLoading();
                }
            },
            async getShopInfo() {
                console.log(this.userInfo.shopId);
                const {
                    code,
                    data
                } = await shopApi.fetchShopInfo(this.userInfo.shopId);
                if (data.prods.length != 0) {
                    this.productList = data.prods;
                }
                if (data.stallNum) {
                    this.stalls = this.transformStallNum(data.stallNum);
                }
                this.order.stallNum = this.stalls[0][0];

                console.log("productList", this.productList);
                console.log("stalls", this.stalls[0][0]);
            },
            //从Storage取数据
            getInfo() {
                //获取用户信息
                const user = uni.getStorageSync('user');
                if (user) {
                    this.userInfo = JSON.parse(user).value;
                    console.log('user', this.userInfo);
                } else {
                    console.log('未找到用户信息');
                }
            },
            toggleView() {
                // 切换显示更多或收起
                this.isOpen = !this.isOpen;
            },
            // 转换摊位的函数
    //         transformStallNum(stallNum) {
    //             const stallsArray = stallNum.split(',').map(item => {
					
				// 	const transformed = item.replace(/(\w+)-(\w+)/, '\$1区\$2号');
					
				// 	return [transformed];
    //                 // const [area, number] = item.split('-');
    //                 // return [`${this.convertArea(area)}${number}号`]; // 形成单个数组以供选择
    //             });
				// console.log(stallsArray);
    //             return stallsArray; // 返回一个二维数组
    //         },
			transformStallNum(stallNum) {
			    const stallsArray = stallNum.split(',').map(item => {
			        // 正则表达式匹配区域-编号，确保能匹配字母和数字
			        const transformed = item.replace(/(\S+)-(\d+)/, '\$1区\$2号'); // 匹配一个或多个非空字符，后接一个连字符和一个或多个数字
			        console.log("transformed:", transformed); // 输出转换后的结果
			        return [transformed]; // 形成单个数组以供选择
			    });
			    console.log("stallsArray:", stallsArray); // 输出二维数组
			    return stallsArray; // 返回二维数组
			},

            // 区域转换函数
            convertArea(area) {
                const areaMap = {
                    '一': '一区',
                    '二': '二区',
                    '三': '三区',
                    '四': '四区',
                };
                return areaMap[area] || area;
            }
        },
        onLoad() {
            this.getInfo();
            // this.fetchProductList();
            this.getShopInfo();
            this.setPickerRange(); // 初始化选择器范围
            // 从 localStorage 中读取之前填写的数据
            const savedData = uni.getStorageSync('orderData');
            if (savedData) {
                this.order = {
                    ...JSON.parse(savedData),
                    senderCar: '', //可能不需要保留这么多
                    senderName: '',
                    senderPhone: '',
                    unloadTime: '',
                    unloadTimeModel: null,
					note: '',
                };
                console.log(savedData);
            }


            // this.order.unloadTimeModel = Number(new Date())
            // this.$refs.datetimePicker.confirm()
        },
        onUnload() {

        },
        computed: {
            displayedProducts() {
                // 根据 isOpen 状态返回要显示的产品列表
                return this.isOpen ? this.productList : this.productList.slice(0, this.max);
            },
            showMoreButton() {
                // 只有当产品数量超过 max 时才显示“更多”按钮
                return this.productList.length > this.max;
            }
        },
        onReady() {
            this.$refs.datetimePicker.setFormatter(this.datetimeFormatter);
            this.$refs.uForm.setRules(this.rules);
        },
        mounted() {

        }
    };
</script>

<style lang="scss">
    .list-scroll-content {
        height: calc(100vh - 70px);
    }

    .plate-button {
        padding: 8upx 16upx;
        // margin: 5px;
        border: 1upx solid #d9a1a1;
        border-radius: 4upx;
        cursor: pointer;
        background-color: #ffe6e6;
    }

    .form-section {

        .u-form-item__body {
            // flex-direction: column !important;
            // align-items: flex-start !important;
        }

        .u-form-item__body__left {
            width: 180rpx !important;
            padding-left: 5px;
            // background: #ffe7e79c;
            // border: solid 1px #FBDBE1;
            border-right: 0;

            text {
                text-align-last: justify !important;
                display: inline !important;
                color: #565656 !important;
            }
        }

        .u-form-item__body__right {
            border-radius: 8px;
            width: 100%;
            background: #f4f5f724;
            /* border: none; */
            border: #ddd 1px solid;

            text {
                // text-align-last: justify !important;
                display: inline !important;
            }

            .u-picker__view__column {
                text {
                    // text-align-last: center !important;
                    display: block !important;
                }
            }

            .prod-input-box {
                margin: 7px;
                border-radius: 8px;
                background: #F4F5F7;
                border: 1px #a6a6a6 dashed;

                .u-input {
                    margin-top: 6px;
                    /* padding-bottom: 6px; */
                    padding-left: 9px;
                    /* padding-right: 9px; */
                    background: #fff;
                    height: 27px;
                    border-radius: 8px;
                    border: 1px #929292 solid;
                }
            }
        }

    }

    .u-form {
        >button {
            margin: 30px 0 50px 0;
            background-color: #0898FF !important;
            border-radius: 8px !important;
            color: #fff !important;
            font-size: 26px !important;
            font-weight: 600 !important;
            width: 86vw !important;
        }

        .u-form-item__body__right__message {
            margin-left: 0px !important;
        }
    }

    .plate-button.plate-add-btn {
        width: 95%;
        text-align: center;
        margin: 7px;
        height: 22px;
        line-height: 16px;
        border-radius: 8px;
        background: transparent;
        border: none;
    }

    .u-notice-bar {
        background-color: #f1f1f1 !important;
    }

    .cell-1 {
        margin: 50rpx 40rpx 0 40rpx;
        // border-left: #ffb9bc 5px solid;
        // background: #ffffff;

        >.u-button {
            background-color: #0898FF !important;
            border-radius: 8px !important;
            color: #fff !important;
            font-size: 26px !important;
            font-weight: 600 !important;
            width: 86vw !important;
        }

        .u-form-item__body__left__content__label {
            font-size: 19px !important;
            font-weight: 600 !important;
        }

        .u-form-item__body__right__content__slot {
            font-size: 16px !important;

            .date-time {
                height: 32px;
                text-align: center;
                line-height: 32px;
            }

            .u-input__content__field-wrapper__field {
                text-align: center !important;
            }

            picker {
                margin-top: 6px;
                /* padding-bottom: 6px; */
                padding-left: 9px;
                /* padding-right: 9px; */
                width: 74.8%;
                background: #fff;
                border: #929292 1px solid;
                border-radius: 8px;
                height: 25px;
            }
        }

        .tit-1 {
            margin: 10rpx 0 0 5px;
            padding-top: 10rpx;
            color: #b5b5b5;
            font-size: 24px;
            font-weight: 600;

            .del-btn {
                padding: 10upx 0 10upx 36upx;
                font-size: $font-lg;
                color: $font-color-light;
                position: relative;

                &:after {
                    content: '';
                    width: 0;
                    height: 30upx;
                    border-left: 1px solid $border-color-dark;
                    position: absolute;
                    left: 20upx;
                    top: 50%;
                    transform: translateY(-50%);
                }
            }
        }

        .content-1 {
            padding: 5px;
        }
    }

    .niceButton4 {
        background-color: #e08181;
        border: none;
        border-radius: 12px;
        color: white;
        /* padding: 15px 32px; */
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        margin: 4px 2px;
        cursor: pointer;
        transition-duration: 0.4s;
        -webkit-transition-duration: 0.4s;
    }

    .niceButton4:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, .24),
            0 17px 50px 0 rgba(0, 0, 0, .19);
    }

    .example-body {
        background-color: #fff;
        padding: 10px;
    }

    .selectGoods-info {
        // min-height: 65vh;
        // max-height: 80vh;
        overflow: scroll;
        // margin-top: 30px;
        // padding: 20px;

        .title {
            font-size: 20px;
            // margin-bottom: 15px;
        }

        .info-item {
            // margin-top: 35px;
            display: flex;

            .info-item-tip {
                font-size: 14px;
                width: 100px;
                padding-left: 30rpx;
            }

            .info-item-content {
                font-size: 18px;
                font-weight: 700;
                width: 74%;
            }
        }
    }

    .product-selection {
        display: flex;
        flex-flow: wrap;
        margin-bottom: 16upx;
    }

    .product-button {
        padding: 8upx 10upx;
        margin: 10px;
        border: 1rpx solid #a1add9;
        border-radius: 4rpx;
        cursor: pointer;
        background-color: #ffffff;
    }

    .product-button.active {
        background-color: #649be8;
        color: white;
    }

    .more-button {
        padding: 8upx 16upx;
        margin: 10px;
        cursor: pointer;
        color: #3482e8;
        text-decoration: underline;
    }

    .selectGoods-info .info-item .info-item-content {
        width: 100% !important;
    }

    .u-button--normal.data-v-6e15e680 {
        font-size: 18px !important;
    }
</style>